package cn.edu.ldu.protocol;

import cn.edu.ldu.controller.FriendController;
import cn.edu.ldu.controller.GroupController;
import cn.edu.ldu.controller.UserController;
import cn.edu.ldu.entity.*;
import cn.edu.ldu.util.Consts;
import cn.edu.ldu.util.L;
import cn.edu.ldu.views.controller.MainUIController;
import cn.edu.ldu.views.main.MainUI;
import cn.edu.ldu.views.operator.AddFriends;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import java.util.HashMap;
import java.util.List;

public class LoginSuccess {

    public LoginSuccess(Protocol protocol){

        HashMap<String, Object> content = JSONObject.parseObject(protocol.getData(), new TypeReference<HashMap<String, Object>>(){});

        L.OK(content, LoginSuccess.class);
        /**
         * 获得个人信息
         */
        UserEntity user = JSONObject.parseObject(content.get(Consts.K_USER_INFO).toString(), UserEntity.class);
        UserAccountEntity account = JSONObject.parseObject(content.get(Consts.K_USER_ACCOUNT).toString(), UserAccountEntity.class);
        List<FriendsEntity> friends = JSONObject.parseArray(content.get(Consts.K_TODO_FRIEND_FRIEND).toString(),FriendsEntity.class);
        UserController.setUserEntity(user);
        UserController.setUserAccountEntity(account);
        UserController.setToken(content.get("token").toString());

//        new AddFriends(friends.get(0)).setVisible(true);
        /**
         * 获得好友
         */
        List<FriendsEntity> onlineFriends = JSONObject.parseArray(content.get(Consts.K_ONLINE_FRIEND).toString(),FriendsEntity.class);
        List<FriendsEntity> offlineFriends = JSONObject.parseArray(content.get(Consts.K_OFFLINE_FRIEND).toString(),FriendsEntity.class);
        List<ChatHistoryEntity> withoutHandleCH = JSONObject.parseArray(content.get(Consts.K_ONLINE_FRIEND).toString(),ChatHistoryEntity.class);
        List<FriendsEntity> withoutHandleFE = JSONObject.parseArray(content.get(Consts.K_ONLINE_FRIEND).toString(),FriendsEntity.class);

        /**
         * 将所有好友都添加到一个list里面
         */
        for(FriendsEntity f : onlineFriends){
            FriendController.addToList(f);
            FriendController.addOnline(f);
        }

        for(FriendsEntity f:offlineFriends){
            FriendController.addToList(f);
        }

        /**
         * 获得分组
         */
        List<GroupChatEntity> groupChatList = JSONObject.parseArray(content.get(Consts.K_GROUP_CHAT).toString(),GroupChatEntity.class);

        /**
         * 将所有分组都添加到一个list
         */
        for (GroupChatEntity g : groupChatList){
            GroupController.addGroupList(g);
        }

        /*
         * 登录成功，进入MainUI
         */
        MainUI mainUI = new MainUI(content);
        mainUI.setVisible(true);
        MainUIController.setMainUI(mainUI);

    }

}
